package org.itboys.mobile.controller.mobile;

import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;
import org.itboys.admin.entity.lasted.SystemDictionary;
import org.itboys.admin.service.lasted.SystemDictionaryService;
import org.itboys.commons.CommonConstants;
import org.itboys.framework.spring.controller.BaseController;
import org.itboys.mobile.common.SundayCommonConstants;
import org.itboys.mobile.dto.SundayMemberSessionDto;
import org.itboys.mobile.dto.wallet.SundayAccountDto;
import org.itboys.mobile.dto.wallet.SundayWalletDto;
import org.itboys.mobile.dto.wallet.SundayWalletRecordDto;
import org.itboys.mobile.entity.mysql.wallet.SundayWallet;
import org.itboys.mobile.service.mongo.front.SundayFrontAccountService;
import org.itboys.mobile.service.mysql.front.SundayFrontWalletRecordService;
import org.itboys.mobile.service.mysql.front.SundayFrontWalletService;
import org.itboys.mobile.util.AccountIdHoldUtils;
import org.itboys.mobile.util.MobileSignUtils;
import org.itboys.mobile.util.ResponseMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Created by zhangyang on 2017/12/19.
 * 圣代_钱包_controller_mobile
 */
@Controller
@RequestMapping("/sunday/mobile/wallet")
public class SundayMobileWalletController extends BaseController{

    @Autowired
    private SundayFrontWalletService walletService;
    @Autowired
    private SundayFrontAccountService cashAccountService;
    @Autowired
    private SundayFrontWalletRecordService walletRecordService;
    @Autowired
    private SystemDictionaryService systemDictionaryService;





    /**
     * 获取钱包
     * @param request
     * @return
     */
    @RequestMapping(value="/getWallet", method={RequestMethod.GET,RequestMethod.POST})
    @ApiOperation("[手机端]我的钱包主体")
    public void getWallet(HttpServletRequest request,
                          HttpServletResponse response,
                          @ApiParam(value = "是否查询优惠券和提现账户。0否1是【参与签名】",required = true)@RequestParam(value = "isIndex", required = true) boolean isIndex,
                          @ApiParam(value = "随机数。【参与签名】")@RequestParam(value = "nonce", required = true) String nonce,
                          @ApiParam(value = "签名")@RequestParam(value = "sign", required = true) String sign){

        try {
            long memberId = AccountIdHoldUtils.getMemberId();
            SundayWalletDto walletDto = walletService.getSingleWalletDto(memberId,isIndex,false,null);
            ResponseMessage.success(walletDto);
        } catch (Exception e) {
            String msg = CommonConstants.ERROMSG;
            Integer code = CommonConstants.FAIL_CODE;
            //自定义异常（签名错误）
            if (e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")) {
                msg = e.getMessage();
                //token已过期
            } else if (e.getClass().getSimpleName().equalsIgnoreCase("TokenException")) {
                code = CommonConstants.TOKEN_CODE;
                msg = CommonConstants.TOKENMSG;
            } else {
                logger.error("/sunday/mobile/wallet/getWallet----e=" + e.getMessage());
            }
            e.printStackTrace();
            ResponseMessage.error(code, msg);
        }
    }

    /**
     * 获取账户余额/积分/爱购币记录
     * @param type 1-余额,2-积分,3-爱购币
     */
    @RequestMapping(value="/record/select", method= {RequestMethod.GET,RequestMethod.POST})
    @ApiOperation("[手机端]获取钱包交易")
    public void record_select(HttpServletRequest request,
                              HttpServletResponse response,
                      @ApiParam(required = false, name = "flag", value = "交易大类型:1-余额,2-积分,3-爱购币,6-贝壳") @RequestParam(value = "flag",required = false) Integer flag,
                       @ApiParam(required = false, name = "type", value = "交易小类型:2-提成,4-提现") @RequestParam(value = "type",required = false) Integer type,
                       @ApiParam(required = true, name = "pageSize", value = "分页参数。每页数量。默认20") @RequestParam(value = "pageSize", required = true) String pageSize,
                       @ApiParam(required = true, name = "pageNumber", value = "分页参数。第几页。默认1") @RequestParam(value = "pageNumber", required = true) String pageNumber,
                       @ApiParam(required = false, name = "sort", value = "排序参数。字段名称。默认为空。销量：saleNumber,价格：price") @RequestParam(value = "sort", required = false) String sort,
                       @ApiParam(required = false, name = "order", value = "排序参数。默认为空。ASC正序/DESC倒序") @RequestParam(value = "order", required = false) String order,
                       @ApiParam(value = "随机数。【参与签名】")@RequestParam(value = "nonce", required = true) String nonce,
                       @ApiParam(value = "签名")@RequestParam(value = "sign", required = true) String sign){
        try {

            Long memberId = AccountIdHoldUtils.getMemberId();
            List<SundayWalletRecordDto> recordList = walletRecordService.getRecord(memberId, flag,type,request);
            ResponseMessage.success(recordList);
        } catch (Exception e) {
            String msg = CommonConstants.ERROMSG;
            Integer code = CommonConstants.FAIL_CODE;
            //自定义异常（签名错误）
            if (e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")) {
                msg = e.getMessage();
                //token已过期
            } else if (e.getClass().getSimpleName().equalsIgnoreCase("TokenException")) {
                code = CommonConstants.TOKEN_CODE;
                msg = CommonConstants.TOKENMSG;
            } else {
                logger.error("/sunday/mobile/wallet/select----e=" + e.getMessage());
            }
            e.printStackTrace();
            ResponseMessage.error(code, msg);
        }
    }

    @RequestMapping(value="/cash/save", method= {RequestMethod.GET,RequestMethod.POST})
    @ApiOperation(value="[手机端]申请提现。先校验调用接口是否绑定微信，否则无法申请提现")
    public void saveApplyCash(
            HttpServletRequest request,
            HttpServletResponse response,
            //@ApiParam(required=true, name="accountId", value="提现账户id.是否参与签名：是")@RequestParam(value = "accountId", required = true)Long accountId,
            @ApiParam(required=true, name="money", value="提现金额[参与签名]")@RequestParam(value = "money", required = true)BigDecimal money,
            @ApiParam(value = "随机数。[参与签名]")@RequestParam(value = "nonce", required = true) String nonce,
            @ApiParam(value = "签名")@RequestParam(value = "sign", required = true) String sign){
        try{
            //2018年1月17日，新增，验证签名
            Map<String, Object> param =new HashMap<String,Object>();
            param.put("nonce", nonce);
            param.put("sign", sign);
           // param.put("accountId",accountId);
            param.put("money",money);
            boolean signSer = MobileSignUtils.signCheck(param, sign);
            if(!signSer){
                logger.warn("签名校验失败");
//                ResponseMessage.error(-1,"签名校验失败");
//                return;
            }
            walletService.saveCash(money,AccountIdHoldUtils.getMemberId(),SundayCommonConstants.pay_type_wechatpay_open);
            ResponseMessage.success();
        }catch (Exception e){
            String msg = CommonConstants.ERROMSG;
            Integer code= CommonConstants.FAIL_CODE;
            //自定义异常（签名错误）
            if(e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")){
                msg=e.getMessage();
                //token已过期
            }else  if(e.getClass().getSimpleName().equalsIgnoreCase("TokenException")){
                code= CommonConstants.TOKEN_CODE;
                msg= CommonConstants.TOKENMSG;
            }else{
                logger.error("/sunday/mobile/wallet/cash/save----e="+e.getMessage());
            }
            e.printStackTrace();
            ResponseMessage.error(code,msg);
        }
    }
    @RequestMapping(value="/conch/charge", method= RequestMethod.POST)
    @ApiOperation(value="【手机端】贝壳充值")
    public void conch_charge(HttpServletRequest request,
                             HttpServletResponse response,
                             //@ApiParam(required=true, name="accountId", value="提现账户id")@RequestParam(value = "accountId", required = true)Long accountId,
                             @ApiParam(required=true, name="number", value="贝壳编码（32位）。前端做好判断")@RequestParam(value = "number", required = true)String number){
        try{
            Long memberId = AccountIdHoldUtils.getMemberId();
            walletService.conch_charge(number,memberId);
            ResponseMessage.success();
        }catch (Exception e){
            String msg = CommonConstants.ERROMSG;
            Integer code= CommonConstants.FAIL_CODE;
            //自定义异常（签名错误）
            if(e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")){
                msg=e.getMessage();
                //token已过期
            }else  if(e.getClass().getSimpleName().equalsIgnoreCase("TokenException")){
                code= CommonConstants.TOKEN_CODE;
                msg= CommonConstants.TOKENMSG;
            }else{
                logger.error("/sunday/mobile/wallet/conch/charge----e="+e.getMessage());
            }
            e.printStackTrace();
            ResponseMessage.error(code,msg);
        }
    }
}
